package com.mmp.main.servlet.joborder;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.bo.Message;
import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.DB.DBQueryManager;
import com.mmp.main.endpoints.JobOrderNotificationsEndPoint;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.entity.JobOrder;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

public class JobOrderDeleteProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String jobOrderId = request.getParameter("jobOrderId");
		String deviceId = request.getParameter("deviceId");

		if (deviceId == null || deviceId.isEmpty() || jobOrderId == null || jobOrderId.isEmpty()) {
			announceErorrMessage(request, response, Default.GENERAL_ERROR_MESSAGE);
			return;
		}

		JobOrder order = dbm.findById(Integer.parseInt(jobOrderId), JobOrder.class);

		HospitalDevice device = order.getHospitalDevice();
		device.setStatus(Enums.DEVICE_STATUS.WORK_PROPERLY.getStatus());
		device = dbm.mergeEntity(device);

		// order.setHospitalDevice(device);
		order.setCancelReason(WebUtil.getParamValue(request, "cancelReason", null));
		order.setCancelled(true);
		order.setCancelledBy(getSessionUser(request));
		order.setCancelledIn(new Date());
		dbm.mergeEntity(order);

		setMessage(request, new Message("تم حذف أمر العمل بنجاح", Message.MESSAGE_TYPE.SUCCESS));
		
		JobOrderNotificationsEndPoint.sendMessageToAll(new DBQueryManager(dbm).getNotification());
		
		sendRedirect(request, response, "SearchForJobOrderDisplay?" + Default.SEARCH_DEST_PARAM_NAME + "="
				+ Default.SEARCH_DEST_CANCEL_JOB_OREDR_PARAM_VALUE);		
	}
}
